package com.example.myapplication.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teautil.models.RuntimeOptions;
import com.example.myapplication.R;
import com.example.myapplication.utils.MD5Utils;
import com.example.myapplication.utils.VerifyCode;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.os.AsyncTask;

import okhttp3.Call;


public class activity_register extends Activity {

    private TextView tv_main_title;//标题
    private Button tv_back;		//返回按钮
    private RelativeLayout rl_title_bar;//标题布局
    private Button btn_register;	//注册按钮
    private EditText et_user_name,et_pwd,et_pwd_again;//用户名、密码、再次输入的密码的控件
    private String username,pwd,pwd_again;//用户名、密码、再次输入的密码的控件的获取值
    private String phoneNum;
    private String sex;
    private Button sendMes;

    // 使用阿里云的 AccessKey 和 AccessKey Secret
    private String accessKeyId = "LTAI5tJ63KieMLZvqoFrcJaW";
    private String accessKeySecret = "hzGmoIgAkMgu0l1oGWe9jcPJIBmWpr";

    private EditText message;

    private String sesContent;   //验证码

    //获取当前时间
    LocalDateTime now;

    // 定义时间格式化器
    DateTimeFormatter formatter;

    //验证码
    private ImageView iv_showCode;
    private EditText et_phoneNum;
    //产生的验证码
    private String realCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        init();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        }
    }
    //验证码
//    private void reacode() {
//
//        //将验证码用图片的形式显示出来
//        iv_showCode.setImageBitmap(CodeUtils.getInstance().createBitmap());
//        realCode =CodeUtils.getInstance().getCode();
//    }
    private void init() {
        // TODO Auto-generated method stub
        //从main_title_bar.xml页面布局中获取对应的UI控件
        //抽取成员变量ctrl+alt+F
        message = (EditText)findViewById(R.id.message);
        sendMes = (Button)findViewById(R.id.sendMes);
        tv_main_title = (TextView) findViewById(R.id.tv_main_title);
        tv_main_title.setText("注册");
        tv_back = ((Button) findViewById(R.id.tv_back));

        //性别选择
        RadioGroup radioGroup = findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = findViewById(checkedId);
                String selectedOption = radioButton.getText().toString();
                // 根据选中的选项进行相应的处理
                if (selectedOption.equals("男")) {
                    // 处理选中男的情况
                    sex = "男";
                } else if (selectedOption.equals("女")) {
                    // 处理选中女的情况
                    sex = "女";
                } else if (selectedOption.equals("保密")) {
                    // 处理选中保密的情况
                    sex = "保密";
                }
            }
        });

        //发送验证码
        sendMes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendMessage();
            }
        });


        //从activity_register.xml页面布局中获取对应的UI控件
        btn_register = (Button) findViewById(R.id.btn_register);
        et_user_name = (EditText) findViewById(R.id.et_user_name);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_pwd_again = (EditText) findViewById(R.id.et_pwd_again);
        //验证码
        et_phoneNum = (EditText) findViewById(R.id.et_PhoneNum);
        iv_showCode = (ImageView) findViewById(R.id.iv_showCode);
//        //图片验证码刷新
//        iv_showCode.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View arg0) {
//                // TODO Auto-generated method stub
//                iv_showCode.setImageBitmap(CodeUtils.getInstance().createBitmap());
//                realCode = CodeUtils.getInstance().getCode();
//            }
//        });
        //注册按钮点击事件
        btn_register.setOnClickListener(new View.OnClickListener() {

            String regEx = "(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,20}$";
            Pattern pattern = Pattern.compile(regEx);
            @Override
            public void onClick(View view) {
                //获取验证码
                String code = message.getText().toString();
                //点击后获取输入在响应控件中的字符串
                getEditstring();
                Matcher matcher = pattern.matcher(pwd);
                if(matcher.matches()){
                    //判断字符串是否为空
                    if(TextUtils.isEmpty(username)){
                        Toast.makeText(activity_register.this, "请输入用户名", Toast.LENGTH_SHORT).show();
                        return;
                    }else if (TextUtils.isEmpty(pwd)){
                        Toast.makeText(activity_register.this, "请输入密码", Toast.LENGTH_SHORT).show();
                        return;
                    }else if (TextUtils.isEmpty(pwd_again)){
                        Toast.makeText(activity_register.this, "请再次输入密码", Toast.LENGTH_SHORT).show();
                        return;
                    }else if (!pwd.equals(pwd_again)) {
                        Toast.makeText(activity_register.this, "两次输入的密码不一样", Toast.LENGTH_SHORT).show();
                        return;
                    }else if(!code.equals(sesContent)){
                        Toast.makeText(activity_register.this, "验证码错误", Toast.LENGTH_SHORT).show();
                    } else {
                        String formattedDateTime = null;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            now = LocalDateTime.now();
                            formattedDateTime = now.format(formatter);
                        }
                        OkHttpUtils
                                .get()
                                .addParams("userid",username)
                                .addParams("username",username)
                                .addParams("password",pwd)
                                .addParams("phone",phoneNum)
                                .addParams("sex",sex)
                                .addParams("reg_time",formattedDateTime)
                                .url("http://121.36.92.128:8086/register")
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int i) {
                                        System.out.println(e.toString());
                                        Toast.makeText(activity_register.this, "此用户已经存在", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onResponse(String response, int i) {

                                        if (response.equals("true")) {
                                            Toast.makeText(activity_register.this, "注册成功", Toast.LENGTH_SHORT).show();
                                            //把用户名和密码保存到SharedPreferences里面
                                            //byOkHttp(username,username,pwd);
                                            saveRegisterInfo(username,pwd);
                                            //注册成功后通过Intent把用户名传递到LoginActivity.java中
                                            Intent data=new Intent();
                                            data.putExtra("username",username);
                                            setResult(RESULT_OK,data);//setResult为OK，关闭当前页面
                                            activity_register.this.finish();//在登录的时候，如果用户还没有注册则注册。注册成功后把注册成功后的用户名返回给前一个页面
                                        }else{
                                            Toast.makeText(activity_register.this, "此用户已经存在", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                           }
                }else{
                    Toast.makeText(activity_register.this, "密码必须同时包含数字与字母,且长度为 6-20位", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //返回按钮
        tv_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                activity_register.this.finish();
            }
        });
    }



    private void saveRegisterInfo(String username, String pwd) {
        String md5Pwd= MD5Utils.MD5(pwd);//把密码用MD5加密
        //loginInfo是sp的文件名
        SharedPreferences sp=getSharedPreferences("loginInfo",MODE_PRIVATE);//通过getSharedPreferences传入loginInfo注册登录相关的信息
        SharedPreferences.Editor editor = sp.edit();//通过sp.edit()获取到sp的编辑器对象
        //username作为key，密码作为value
        editor.putString(username,md5Pwd);
        editor.commit();//提交修改
    }

    /**
     * 从SharedPreferences中读取输入的用户名，判断SharedPreferences中是否有用户名
     * @return
     */
//    private boolean isExistUserName(String username) {
//        boolean has_userName=false;//表示是否有用户名
//        SharedPreferences sp=getSharedPreferences("loginInfo",MODE_PRIVATE);
//        String spPwd = sp.getString(username,""); //通过sp.getString传值用户名获取到密码
//        if (!TextUtils.isEmpty(spPwd)){ //判断这个密码是否为空
//            has_userName=true;//该用户是否保存了这一个密码
//        }
//        return has_userName;
//    }
    public Boolean byOkHttpUtils(String userId,String userName,String password,String number,String sex){
        Boolean[] flag = {false};


        return flag[0];
    }
    /**
     * 获取控件中的字符串
     */
    private void getEditstring() {
        username=et_user_name.getText().toString().trim();
        pwd = et_pwd.getText().toString();
        pwd_again = et_pwd_again.getText().toString().trim();
        phoneNum = et_phoneNum.getText().toString().trim();
    }


    private void sendMessage() {
        String phoneNumber = et_phoneNum.getText().toString();
        if (phoneNumber.isEmpty()) {
            Toast.makeText(activity_register.this, "请输入手机号", Toast.LENGTH_SHORT).show();
        } else {
            new SendSmsTask().execute(phoneNumber);
        }
    }

//    private void sendMessage()
//    {
//        String phoneNumber = et_phoneNum.getText().toString();
//        Random random = new Random();
//        if(phoneNumber.isEmpty()){
//            Toast.makeText(activity_register.this, "请输入手机号", Toast.LENGTH_SHORT).show();
//        }else{
//            int min = 1000; // 最小的四位数是 1000
//            int max = 9999; // 最大的四位数是 9999
//            sesContent = String.valueOf(random.nextInt(max - min + 1) + min);
//            String code = sesContent;
//            // 创建短信客户端
//            Client client = null;
//            try {
//                client = VerifyCode.createClient(accessKeyId, accessKeySecret);
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//            // 创建发送短信请求
//            SendSmsRequest sendSmsRequest = new SendSmsRequest()
//                    .setPhoneNumbers(phoneNumber)
//                    .setSignName("商场定位")
//                    .setTemplateCode("SMS_282625177")
//                    .setTemplateParam("{\"code\":\"" + code + "\"}");
//            try {
//                // 发送短信
//                RuntimeOptions runtime = new RuntimeOptions();
//                com.aliyun.dysmsapi20170525.models.SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
//                // 在这里处理发送成功的逻辑
//                Toast.makeText(activity_register.this,"验证码发送成功",Toast.LENGTH_SHORT).show();
//            } catch (Exception e) {
//                e.printStackTrace();
//                // 在这里处理发送失败的逻辑
//                Toast.makeText(activity_register.this, "发送失败", Toast.LENGTH_SHORT).show();
//            }
//        }
//    }

    private class SendSmsTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String phoneNumber = params[0];
            Random random = new Random();
            int min = 1000;
            int max = 9999;
            sesContent = String.valueOf(random.nextInt(max - min + 1) + min);
            String code = sesContent;

            // 创建短信客户端
            Client client = null;
            try {
                client = VerifyCode.createClient(accessKeyId, accessKeySecret);
            } catch (Exception e) {
                // 处理异常情况
                return "创建短信客户端失败";
            }

            // 创建发送短信请求
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName("商场定位")
                    .setTemplateCode("SMS_461985455")
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            try {
                // 发送短信
                RuntimeOptions runtime = new RuntimeOptions();
                com.aliyun.dysmsapi20170525.models.SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
                // 在这里处理发送成功的逻辑
                System.out.println(resp.toString());
                return "验证码发送成功";
            } catch (Exception e) {
                e.printStackTrace();
                // 在这里处理发送失败的逻辑
                return "发送失败";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            // 在任务执行完成后，更新UI或进行其他操作
            Toast.makeText(activity_register.this, result, Toast.LENGTH_SHORT).show();
        }
    }
}
